/**
 * 
 */
package com.android.gtdroid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;

/**
 * @author xiang
 * 
 */
public class MySimpleExpandableListAdapter extends SimpleExpandableListAdapter {

	private final String TAG = "MySimpleExpandableListAdapter";
	
	private Context mContext;
	private GTDApp ga;
	private LayoutInflater mInflater;
	private ArrayList<HashMap<String, Object>> groupData;
	private ArrayList<ArrayList<HashMap<String, Object>>> childData;
	private int taskStatus = C.TASK.UNCOMPLETED;
	private int groupLayout;
	private String[] groupFrom;
	private int[] groupTo;
	private int actType;

	
	private static class ViewHolder {
		TextView prior;
		CheckBox cb;
		TextView title;
		// ImageView image;
		TextView context;
		TextView position;
		TextView project;
		TextView tags;

		TextView flag;
	}

	@SuppressWarnings("unchecked")
	public MySimpleExpandableListAdapter(Context context, int actType,
			List<? extends Map<String, ?>> groupData, int groupLayout,
			String[] groupFrom, int[] groupTo,
			List<? extends List<? extends Map<String, ?>>> childData,
			int childLayout, String[] childFrom, int[] childTo) {
		super(context, groupData, groupLayout, groupFrom, groupTo, childData,
				childLayout, childFrom, childTo);
		// TODO Auto-generated constructor stub

		this.actType = actType;
		switch (actType) {
		case C.ADAPTER.VIEWTASK:
			mContext = (ViewTaskAct) context;
			ga = (GTDApp) ((ViewTaskAct) context).getApplication();
			break;

		case C.ADAPTER.CONTEXT:
			mContext = (ContextAct) context;
			ga = (GTDApp) ((ContextAct) context).getApplication();
			break;
			
		case C.ADAPTER.SEARCH:
			mContext = (SearchAct) context;
			ga = (GTDApp) ((SearchAct) context).getApplication();
			break;

		default:
			break;
		}

		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.groupData = (ArrayList<HashMap<String, Object>>) groupData;
		this.childData = (ArrayList<ArrayList<HashMap<String, Object>>>) childData;
		this.groupLayout = groupLayout;
		this.groupFrom = groupFrom;
		this.groupTo = groupTo;
	}

	@Override
	public View getChildView(final int groupPosition, final int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View v = null;

		switch (actType) {
		case C.ADAPTER.VIEWTASK:
			v = getViewTaskChildView(mContext, groupPosition, childPosition, isLastChild,
					convertView, parent);
			break;

		case C.ADAPTER.CONTEXT:
			v = getContextChildView(mContext, groupPosition, childPosition, isLastChild,
					convertView, parent);
			break;
			
		case C.ADAPTER.SEARCH:
			v = getSearchChildView(mContext, groupPosition, childPosition, isLastChild,
					convertView, parent);
			break;

		default:
			break;
		}

		return v;
	}
	
	private View getSearchChildView(Context context, final int groupPosition,
			final int childPosition, boolean isLastChild, View convertView,
			ViewGroup parent) {

		final ViewHolder holder;

		SearchAct vtaContext = (SearchAct) context;
		
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.row_task, null);

			holder = new ViewHolder();
			holder.prior = (TextView) convertView
					.findViewById(R.id.tv_row_prior);

			Log.e(TAG, "convertView is empty: group:"+groupPosition+" children:"+childPosition);

			holder.cb = (CheckBox) convertView.findViewById(R.id.cb_completed);
//			holder.cb.setTag(childPosition);
			holder.title = (TextView) convertView.findViewById(R.id.tv_task);
			// holder.image = (ImageView)
			// convertView.findViewById(R.id.iv_image);
			holder.context = (TextView) convertView
					.findViewById(R.id.tv_row_context);
			holder.position = (TextView) convertView
					.findViewById(R.id.tv_row_pos);
			// holder.project = (TextView)
			// convertView.findViewById(R.id.tv_row_prj);
			holder.tags = (TextView) convertView.findViewById(R.id.tv_row_tag);
			holder.flag = (TextView) convertView.findViewById(R.id.tv_row_flag);

			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
//			holder.cb.setChecked(false);
//			holder.cb.setTag(childPosition);
			
			Log.e(TAG, "convertView not empty: group:"+groupPosition+" children:"+childPosition);

			/*
			 * if (taskStatus != C.TASK.CANCELLED)
			 * holder.cb.setTag(childPosition);
			 */
		}

		/* ------- bind view ------ */
		int flag = 0;
		String prior = (String) childData.get(groupPosition).get(childPosition)
				.get("item_prior");
		if (prior.equals("无"))
			flag = 0;
		else if (prior.equals("高"))
			flag = 1;
		else if (prior.equals("中"))
			flag = 2;
		else if (prior.equals("低"))
			flag = 3;

		switch (flag) {
			case 0:
				holder.prior.setBackgroundColor(0xff444444);
				break;
	
			case 1:
				holder.prior.setBackgroundColor(0xffff0000);
				break;
	
			case 2:
				holder.prior.setBackgroundColor(0xff0000ff);
				break;
	
			case 3:
				holder.prior.setBackgroundColor(0xff87cefa);
				break;
	
			default:
				break;
		}

		if (holder.cb.isChecked())
			Log.e(TAG, "children["+groupPosition+"]["+childPosition+"] is checked");
		else
			Log.e(TAG, "children["+groupPosition+"]["+childPosition+"] is unchecked");
		
		int state = (Integer) childData.get(groupPosition).get(childPosition).get("item_completed");
		if (state == C.TASK.COMPLETED)
			holder.cb.setChecked(true);
		
		holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				Log.e("adapter", "checkbox " + childPosition + " checked!");

				/*@SuppressWarnings("unchecked")
				HashMap<String, Object> hm = (HashMap<String, Object>) getChild(
						groupPosition, childPosition);*/
				HashMap<String, Object> hm = childData.get(groupPosition).get(childPosition);
				long rowId = (Long) hm.get("item_id");
				TaskItem ti = ga.getDbta().getTaskItem(rowId);

				if (isChecked) {
					holder.flag.setVisibility(View.VISIBLE);

					ti.setCompletedStatus(C.TASK.COMPLETED);
					ga.getDbta().updateTask(rowId, ti);
				} else {
					holder.flag.setVisibility(View.INVISIBLE);

					ti.setCompletedStatus(C.TASK.UNCOMPLETED);
					ga.getDbta().updateTask(rowId, ti);
				}
				
				buttonView.setTag(null);
			}
		});
		
		holder.title.setText((String) childData.get(groupPosition)
				.get(childPosition).get("item_name"));

		String ctt = (String) childData.get(groupPosition).get(childPosition)
				.get("item_context");
		if (ctt.equals(ga.getContexts().get(0))) // no context
			holder.context.setText("");
		else
			holder.context.setText("@" + ctt);

		String pos = (String) childData.get(groupPosition).get(childPosition)
				.get("item_pos");
		if (pos.equals(ga.getPositions().get(0)))
			holder.position.setText("");
		else
			holder.position.setText("&" + pos);

		/*
		 * String prj = (String)
		 * childData.get(groupPosition).get(childPosition).get("item_project");
		 * if (prj.equals(ga.getProjects().get(0))) holder.project.setText("");
		 * else holder.project.setText("#"+prj);
		 */

		holder.tags.setText((String) childData.get(groupPosition)
				.get(childPosition).get("item_tags"));
		
		// setting to default (fix this bug)
		holder.flag.setVisibility(View.INVISIBLE);
		
		return convertView;
	}

	private View getContextChildView(Context context, final int groupPosition,
			final int childPosition, boolean isLastChild, View convertView,
			ViewGroup parent) {

		final ViewHolder holder;

		ContextAct vtaContext = (ContextAct) context;
		
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.row_task, null);

			holder = new ViewHolder();
			holder.prior = (TextView) convertView
					.findViewById(R.id.tv_row_prior);

			Log.e(TAG, "convertView is empty: group:"+groupPosition+" children:"+childPosition);

			holder.cb = (CheckBox) convertView.findViewById(R.id.cb_completed);
//			holder.cb.setTag(childPosition);
			holder.title = (TextView) convertView.findViewById(R.id.tv_task);
			// holder.image = (ImageView)
			// convertView.findViewById(R.id.iv_image);
			holder.context = (TextView) convertView
					.findViewById(R.id.tv_row_context);
			holder.position = (TextView) convertView
					.findViewById(R.id.tv_row_pos);
			// holder.project = (TextView)
			// convertView.findViewById(R.id.tv_row_prj);
			holder.tags = (TextView) convertView.findViewById(R.id.tv_row_tag);
			holder.flag = (TextView) convertView.findViewById(R.id.tv_row_flag);

			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
//			holder.cb.setChecked(false);
//			holder.cb.setTag(childPosition);
			
			Log.e(TAG, "convertView not empty: group:"+groupPosition+" children:"+childPosition);

			/*
			 * if (taskStatus != C.TASK.CANCELLED)
			 * holder.cb.setTag(childPosition);
			 */
		}

		/* ------- bind view ------ */
		int flag = 0;
		String prior = (String) childData.get(groupPosition).get(childPosition)
				.get("item_prior");
		if (prior.equals("无"))
			flag = 0;
		else if (prior.equals("高"))
			flag = 1;
		else if (prior.equals("中"))
			flag = 2;
		else if (prior.equals("低"))
			flag = 3;

		switch (flag) {
			case 0:
				holder.prior.setBackgroundColor(0xff444444);
				break;
	
			case 1:
				holder.prior.setBackgroundColor(0xffff0000);
				break;
	
			case 2:
				holder.prior.setBackgroundColor(0xff0000ff);
				break;
	
			case 3:
				holder.prior.setBackgroundColor(0xff87cefa);
				break;
	
			default:
				break;
		}

		if (holder.cb.isChecked())
			Log.e(TAG, "children["+groupPosition+"]["+childPosition+"] is checked");
		else
			Log.e(TAG, "children["+groupPosition+"]["+childPosition+"] is unchecked");
		
//		int state = (Integer) childData.get(groupPosition).get(childPosition).get("item_completed");
//		if (state == C.TASK.COMPLETED)
//			holder.cb.setChecked(false);
		
		holder.cb.setOnCheckedChangeListener(null);
		holder.cb.setChecked(false);		// fix this bug
		holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				Log.e("adapter", "checkbox " + childPosition + " checked!");

				/*@SuppressWarnings("unchecked")
				HashMap<String, Object> hm = (HashMap<String, Object>) getChild(
						groupPosition, childPosition);*/
				HashMap<String, Object> hm = childData.get(groupPosition).get(childPosition);
				long rowId = (Long) hm.get("item_id");
				TaskItem ti = ga.getDbta().getTaskItem(rowId);

				if (isChecked) {
					holder.flag.setVisibility(View.VISIBLE);

					ti.setCompletedStatus(C.TASK.COMPLETED);
					ga.getDbta().updateTask(rowId, ti);
				} else {
					holder.flag.setVisibility(View.INVISIBLE);

					ti.setCompletedStatus(C.TASK.UNCOMPLETED);
					ga.getDbta().updateTask(rowId, ti);
				}
				
				buttonView.setTag(null);
			}
		});
		
		holder.title.setText((String) childData.get(groupPosition)
				.get(childPosition).get("item_name"));

		String ctt = (String) childData.get(groupPosition).get(childPosition)
				.get("item_context");
		if (ctt.equals(ga.getContexts().get(0))) // no context
			holder.context.setText("");
		else
			holder.context.setText("@" + ctt);

		String pos = (String) childData.get(groupPosition).get(childPosition)
				.get("item_pos");
		if (pos.equals(ga.getPositions().get(0)))
			holder.position.setText("");
		else
			holder.position.setText("&" + pos);

		/*
		 * String prj = (String)
		 * childData.get(groupPosition).get(childPosition).get("item_project");
		 * if (prj.equals(ga.getProjects().get(0))) holder.project.setText("");
		 * else holder.project.setText("#"+prj);
		 */

		holder.tags.setText((String) childData.get(groupPosition)
				.get(childPosition).get("item_tags"));
		
		// setting to default (fix this bug)
		holder.flag.setVisibility(View.INVISIBLE);
		
		return convertView;
	}

	private View getViewTaskChildView(Context context, final int groupPosition,
			final int childPosition, boolean isLastChild, View convertView,
			ViewGroup parent) {

		final ViewHolder holder;

		// View view = super.getView(position, convertView, parent);
		ViewTaskAct vtaContext = (ViewTaskAct) context;
		taskStatus = vtaContext.getTaskStatus();

		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.row_task, null);

			holder = new ViewHolder();
			holder.prior = (TextView) convertView
					.findViewById(R.id.tv_row_prior);

			if (taskStatus == C.TASK.CANCELLED) { // remove the checkbox
				LinearLayout ll_row_top = ((LinearLayout) convertView
						.findViewById(R.id.ll_row_top));
				LinearLayout ll_row_cb = ((LinearLayout) convertView
						.findViewById(R.id.ll_row_cb));
				ll_row_top.removeView(ll_row_cb);
			} else {
				holder.cb = (CheckBox) convertView
						.findViewById(R.id.cb_completed);
//				holder.cb.setTag(childPosition);
			}

			holder.title = (TextView) convertView.findViewById(R.id.tv_task);
			// holder.image = (ImageView)
			// convertView.findViewById(R.id.iv_image);
			holder.context = (TextView) convertView
					.findViewById(R.id.tv_row_context);
			holder.position = (TextView) convertView
					.findViewById(R.id.tv_row_pos);
			// holder.project = (TextView)
			// convertView.findViewById(R.id.tv_row_prj);
			holder.tags = (TextView) convertView.findViewById(R.id.tv_row_tag);
			holder.flag = (TextView) convertView.findViewById(R.id.tv_row_flag);

			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();

//			if (taskStatus != C.TASK.CANCELLED)
//				holder.cb.setTag(childPosition);
		}

		/* ------- bind view ------ */
		int flag;
		String prior = (String) childData.get(groupPosition).get(childPosition)
				.get("item_prior");
		if (prior.equals("无"))
			flag = 0;
		else if (prior.equals("高"))
			flag = 1;
		else if (prior.equals("中"))
			flag = 2;
		else
			// ��
			flag = 3;

		switch (flag) {
		case 0:
			holder.prior.setBackgroundColor(0xff444444);
			break;

		case 1:
			holder.prior.setBackgroundColor(0xffff0000);
			break;

		case 2:
			holder.prior.setBackgroundColor(0xff0000ff);
			break;

		case 3:
			holder.prior.setBackgroundColor(0xff87cefa);
			break;

		default:
			break;
		}

		if (taskStatus != C.TASK.CANCELLED) {
			if (vtaContext.getTaskStatus() == C.TASK.COMPLETED)
				holder.cb.setChecked(true);
			holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					// TODO Auto-generated method stub
					Log.e("adapter", "checkbox " + childPosition + " checked!");

					HashMap<String, Object> hm = childData.get(groupPosition).get(childPosition);
					long rowId = (Long) hm.get("item_id");
					TaskItem ti = ga.getDbta().getTaskItem(rowId);

					if (isChecked) {
						holder.flag.setVisibility(View.VISIBLE);

						ti.setCompletedStatus(C.TASK.COMPLETED);
						ga.getDbta().updateTask(rowId, ti);
					} else {
						holder.flag.setVisibility(View.INVISIBLE);

						ti.setCompletedStatus(C.TASK.UNCOMPLETED);
						ga.getDbta().updateTask(rowId, ti);
					}
				}
			});
		}

		holder.title.setText((String) childData.get(groupPosition)
				.get(childPosition).get("item_name"));

		String ctt = (String) childData.get(groupPosition).get(childPosition)
				.get("item_context");
		if (ctt.equals(ga.getContexts().get(0))) // no context
			holder.context.setText("");
		else
			holder.context.setText("@" + ctt);

		String pos = (String) childData.get(groupPosition).get(childPosition).get("item_pos");
		if (pos.equals(ga.getPositions().get(0)))
			holder.position.setText("");
		else
			holder.position.setText("&" + pos);

		/*
		 * String prj = (String)
		 * childData.get(groupPosition).get(childPosition).get("item_project");
		 * if (prj.equals(ga.getProjects().get(0))) holder.project.setText("");
		 * else holder.project.setText("#"+prj);
		 */

		holder.tags.setText((String) childData.get(groupPosition)
				.get(childPosition).get("item_tags"));

		return convertView;
	}

	@Override
	public View newGroupView(boolean isExpanded, ViewGroup parent) {
		// TODO Auto-generated method stub
		// return super.newGroupView(isExpanded, parent);
		
		View v = null;

		switch (actType) {
			case C.ADAPTER.VIEWTASK:
				v = newViewTaskGroupView(isExpanded, parent);
				break;
	
			case C.ADAPTER.CONTEXT:
				v = newContextGroupView(isExpanded, parent);
				break;
				
			case C.ADAPTER.SEARCH:
				v = newSearchGroupView(isExpanded, parent);
				break;
	
			default:
				break;
		}

		return v;
		 

//		return mInflater.inflate(R.layout.group, parent, false);
	}

	
	private View newViewTaskGroupView(boolean isExpanded, ViewGroup parent) {
		
		ViewTaskAct vtaContext = (ViewTaskAct) mContext;
		
		int index = vtaContext.getSortIndex();
		if (index > 0)
			return 	mInflater.inflate(R.layout.group, parent, false);
		else 
			return mInflater.inflate(R.layout.empty, parent, false);

	}

	private View newContextGroupView(boolean isExpanded, ViewGroup parent) {

//		int index = context.getSortIndex();
//		if (index > 0)
//			return mInflater.inflate(R.layout.group, parent, false);
//		else
//			return mInflater.inflate(R.layout.empty, parent, false);
		
		return mInflater.inflate(R.layout.grp_context, parent, false);
	}
	
	private View newSearchGroupView(boolean isExpanded, ViewGroup parent) {

//		int index = context.getSortIndex();
//		if (index > 0)
//			return mInflater.inflate(R.layout.group, parent, false);
//		else
//			return mInflater.inflate(R.layout.empty, parent, false);
		
		return mInflater.inflate(R.layout.grp_search, parent, false);
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View v;
		v = newGroupView(isExpanded, parent);

		bindGroupView(v, groupData.get(groupPosition), groupFrom, groupTo);

		return v;
	}

	private void bindGroupView(View view, Map<String, Object> data,
			String[] from, int[] to) {
		int len = to.length;

		for (int i = 0; i < len; i++) {
			TextView v = (TextView) view.findViewById(to[i]);
			if (v != null) {
				v.setText((String) data.get(from[i]));
			}
		}
	}

}
